package com.quectel.emp.controller.device;

import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.business.common.alarm.DataProcessingComponent;
import com.quectel.constant.core.alarm.AlarmConstants;
import com.quectel.core.module.alarm.dto.AlarmRuleDto;
import com.quectel.core.module.alarm.dto.HandAlarmRuleInfo;
import com.quectel.core.module.dept.dto.DeptPersonDto;
import com.quectel.core.module.device.dto.DeviceCurrentAlarmDto;
import com.quectel.core.module.device.dto.DeviceDto;
import com.quectel.core.module.device.service.DeviceCurrentAlarmService;
import com.quectel.core.module.device.service.DeviceService;
import com.quectel.emp.controller.BaseController;
import com.quectel.emp.util.SessionHolder;
import com.quectel.util.common.JacksonUtils;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * @author rananxin
 * @email ryan.ran@quectel.com
 * @date 2022/6/6 10:33
 */
@RestController
@RequestMapping("alarmManager")
@Tag(name = "AlarmManagerController", description = "告警管理相关的api")
public class AlarmManagerController extends BaseController {

    @DubboReference
    private DeviceService deviceService;
    @DubboReference
    private DeviceCurrentAlarmService deviceCurrentAlarmService;
    @Autowired
    private DataProcessingComponent dataProcessingComponent;

    /**
     * 告警恢复
     *
     * @param ids
     * @return
     */
    @PostMapping("restore")
    @Operation(summary = "批量告警恢复")
    public Response<Object> recover(@Parameter(description = "id数组") @RequestBody Long[] ids) {
        for (Long id : ids) {
            DeviceCurrentAlarmDto deviceCurrentAlarmDto = deviceCurrentAlarmService.selectById(id);
            if (deviceCurrentAlarmDto == null) {
                continue;
            }
            dataProcessingComponent.recoverCurrentAlarm(deviceCurrentAlarmDto, AlarmConstants.ALARM_MANUAL_CLOSE_TYPE);

            //告警状态重置
            DeviceDto deviceDto = deviceService.selectById(deviceCurrentAlarmDto.getDeviceId());
            dataProcessingComponent.updateAlarmStatusAndMergeLastData(deviceDto, new HashMap<>());

            if (StringUtils.isNotBlank(deviceCurrentAlarmDto.getAlarmDetailJson())) {
                //处理事件或者工单
                HandAlarmRuleInfo handAlarmRuleInfo = new HandAlarmRuleInfo();
                handAlarmRuleInfo.setAlarmConformLevel(AlarmConstants.ALARM_NO);
                handAlarmRuleInfo.setAlarmRuleDto(JacksonUtils.parse(deviceCurrentAlarmDto.getAlarmDetailJson(), AlarmRuleDto.class));


                dataProcessingComponent.handleAlarmEventAndWorkOrder(deviceDto,
                        new DataProcessingComponent.HandleAlarmResp(
                                new ArrayList<>(Arrays.asList(handAlarmRuleInfo)),
                                deviceCurrentAlarmService.queryByDeviceId(deviceCurrentAlarmDto.getDeviceId())
                        )
                );

            }

        }
        return Response.ok();
    }

    @GetMapping("list")
    @Operation(summary = "告警日志分页查询列表")
    public Response<Page<DeviceCurrentAlarmDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize,
            @Parameter(description = "imei") @RequestParam(required = false) String imei,
            @Parameter(description = "搜索框输入内容:模糊匹配 名称,imei,地址,deviceCode") @RequestParam(required = false) String queryString,
            @Parameter(description = "deviceCode") @RequestParam(required = false) String deviceCode,
            @Parameter(description = "在线状态 0离线 1在线") @RequestParam(required = false) Byte onlineStatus
    ) {
        SessionHolder.checkEmp();
        DeptPersonDto emp = SessionHolder.getEmp();
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        assert emp != null;
        if (StringUtils.isNotBlank(request.getString("imei"))) {
            DeviceDto deviceInfo = deviceService.selectCacheByImei(request.getString("imei"), emp.getTenantId());
            if (deviceInfo == null) {
                request.put("deviceId", "-1");
            } else {
                request.put("deviceId", deviceInfo.getId());
            }
        }

        request.put(LambdaUtil.getFieldName(DeviceDto::getVillage), emp.getVillageId());

        int total = deviceCurrentAlarmService.queryTotal(request.getParams());
        List<DeviceCurrentAlarmDto> list = new ArrayList<>();
        if (total > 0) {
            list = deviceCurrentAlarmService.queryListLessPadding(request.getParams());
        }
        Page<DeviceCurrentAlarmDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<DeviceCurrentAlarmDto>>ok().wrap(page);
    }
}
